import React from 'react';
import { Route, Redirect } from 'react-router-dom';

const renderRoutes = (config, app = 'app', routes = [], parent) => {
  config.forEach((route, i) => {
    const { routes: children, ...routeProps } = route;
    const key = route.key || (parent ? `${parent.key}-${i}` : i);

    routes.push(
      <Route
        key={`${app}-${key}`}
        path={route.path}
        replace
        exact={!children}
        render={
          (props) => {
            const { path, redirect, component: Page, ...pageProps } = routeProps;
            if (children) {
              const childrenConfig = [routeProps].concat(children);
              return renderRoutes(childrenConfig, app, [], routeProps);
            }
            if (redirect) return <Redirect to={redirect} replace exact />;
            return <Page { ...props } { ...pageProps } />
          }
        }
      />
    );
  });
  return routes;
};

export default renderRoutes;
